package com.example.demo.config.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.demo.common.dto.MessageDTO;
import com.example.demo.config.service.RocketMQProducerService;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.springframework.stereotype.Service;

/**
 * @author yongen
 * @description:
 * @date 2022/2/9 2:34 PM
 */
@Service
@Slf4j
public class RocketMQProducerServiceImpl implements RocketMQProducerService {

  @Resource
  private DefaultMQProducer defaultProducer;

  @Override
  public boolean sendMessage(MessageDTO messageDTO) {
    SendResult sendResult;
    try{
      Message message = messageDTO.getMessage();
      log.info("开始发送同步消息, message:{}", JSON.toJSONString(message));
      sendResult = defaultProducer.send(message);
    }catch (Exception e){
      log.error("消息同步发送失败, messageDTO={}, cause:{}", JSON.toJSONString(messageDTO), e);
      return false;
    }
    if (SendStatus.SEND_OK.equals(sendResult.getSendStatus())) {
      log.info("消息同步发送成功, sendResult:{}", JSON.toJSONString(sendResult));
      messageDTO.setMsgId(sendResult.getMsgId());
      return true;
    }
    return false;
  }

  @Override
  public void sendSyncMessage(MessageDTO messageDTO, SendCallback sendCallback) {
    Message message = messageDTO.getMessage();
    log.info("开始发送异步消息, message:{}", JSON.toJSONString(message));
    try {
      defaultProducer.send(message, sendCallback);
    }catch (Exception e){
      log.error("消息异步发送失败, messageDTO={}, cause:{}", JSON.toJSONString(messageDTO), e);
    }
  }

  @Override
  public void sendOnewayMessage(MessageDTO messageDTO) {
    Message message = messageDTO.getMessage();
    log.info("开始发送单向消息, message:{}", JSON.toJSONString(message));
    try {
      defaultProducer.sendOneway(message);
    }catch (Exception e){
      log.error("消息单向发送失败, messageDTO={}, cause:{}", JSON.toJSONString(messageDTO), e);
    }
  }
}
